/*
 * Created by SharpDevelop.
 * User: rseward
 * Date: 6/4/2008
 * Time: 10:05 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace AvvaMobileNHibernateHelperKit
{
	/// <summary>
	/// Description of XmlUtils.
	/// </summary>
	public class XmlUtils
	{
		public XmlUtils()
		{
		}
		
		public static string Write(object xmlObjTree)
		{
			return ToXmlUtf8( xmlObjTree );
			/*
			XmlSerializer serializer = new XmlSerializer(xmlObjTree.GetType());
			
			StringWriter sw = new StringWriter();
			serializer.Serialize( sw, xmlObjTree );
			sw.Close();
			
			return sw.ToString(); */
		}
		
		public static string ToXml( object xmlobjtree )
		{
			return ToXmlUtf8( xmlobjtree );
		}
		
		public static string ToXmlUtf8( object xmlobjtree )
		{
			// Because MSIX requires UTF8 not UTF16 we have to jump thru
			//   these hoops to generate the XML.
			MemoryStream memStream = new MemoryStream();
			XmlWriterSettings settings = new XmlWriterSettings();
			settings.Encoding = new UTF8Encoding(false);
			settings.ConformanceLevel = ConformanceLevel.Document;
			settings.Indent = true;
			
			using (XmlWriter xmlWriter = XmlWriter.Create(memStream, settings)) 
			{
				XmlSerializer xmlout = new XmlSerializer( xmlobjtree.GetType() );
				
				xmlout.Serialize(xmlWriter, xmlobjtree);
				
				xmlWriter.Flush();
				xmlWriter.Close();
			}
			
			return Encoding.UTF8.GetString(memStream.ToArray());
		}
		
		
		public static object ParseXml(object objectTree, string xml)
        {

            StringReader objReader = new StringReader(xml);
            XmlSerializer xmlparser = new XmlSerializer(objectTree.GetType());
            object result = xmlparser.Deserialize(objReader);

            return result;
        }
		
	}
}
